package com.itborder.MargeMV;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.ref.WeakReference;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ProgressBar;

public class MargeMVActivity extends Activity {

	private Button btMerge;
    private EditText tInput;
    private EditText tOutput;
    private TextView tvProgress;
    private ProgressBar PB;
    private TextView tvTip;
    private TextView tvCount;

    private int iProgress = 0;
    
    private String tvCount_text = "";
    private String tvTip_text = "";
    
    
    protected static final int UPDATE_PROGRESS = 0x1000;
    protected static final int FINISHED = 0x1001;
    protected static final int UPDATE_COUNT = 0x1002;
    protected static final int UPDATE_TIP = 0x1003;
    

	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        btMerge = (Button)this.findViewById(R.id.btMerge);
        tInput = (EditText)this.findViewById(R.id.tInput);
        tOutput = (EditText)this.findViewById(R.id.tOutput);
        tvProgress = (TextView)this.findViewById(R.id.tvProgress);
        PB = (ProgressBar)this.findViewById(R.id.PB);
        tvTip = (TextView)this.findViewById(R.id.tvTip);
        tvCount = (TextView)this.findViewById(R.id.tvCount);
        
        btMerge.setOnClickListener(btMerge_listener);
    }
    
    
    OnClickListener btMerge_listener = new OnClickListener() {
    	@Override
    	public void onClick(View v) {
        	Toast.makeText(getApplicationContext(), "开始合并，请稍候......", Toast.LENGTH_SHORT).show();
        	
        	//btMerge.setText("合并中");
        	btMerge.setEnabled(false);
        	tInput.setEnabled(false);
        	tOutput.setEnabled(false);
        	tvProgress.setText("0%");
        	tvTip.setText("");
        	tvCount.setText("");
        	PB.setProgress(0);
        	
        	if (!tOutput.getText().toString().substring(tOutput.getText().toString().length()-1).equals("/")) 
        		tOutput.setText(tOutput.getText().toString() + "/");
        	
        	//开启线程进行处理。
        	Thread aThread = new Thread(new Runnable() {
        		public void run () {
        			
        			//判断目标目录是否存在
        			File fOutputPath = new File(tOutput.getText().toString());
        			if (!fOutputPath.exists()) {
        				if (!fOutputPath.mkdir()) {
        					Toast.makeText(getApplicationContext(), "输出文件夹创建失败！", Toast.LENGTH_SHORT).show();
        					return;
        				}
        			}
        			
        			File fInputPath = new File(tInput.getText().toString());
        			if (!fInputPath.exists()) {
        				Toast.makeText(getApplicationContext(), "源文件夹不存在！", Toast.LENGTH_SHORT).show();
        				return;
        			}
        			
        			File[] fInputFiles = fInputPath.listFiles();
        			if (fInputFiles.length==0)
        			{
        				Toast.makeText(getApplicationContext(), "没有要合并的文件！", Toast.LENGTH_SHORT).show();
        				return;
        			}
        			
        			tvCount_text = "共有" + fInputFiles.length + "段视频：\n";
        			for (int i=0;i<fInputFiles.length;i++) {
        				tvCount_text += GetMVName(fInputFiles[i]) + "\n";
        			}
        			Message msgc = new Message();
        			msgc.what = UPDATE_COUNT;
        			mHandler.sendMessage(msgc);
        			
        			for (int i=0; i<fInputFiles.length; i++) {
        				File[] fmvs = fInputFiles[i].listFiles();
        				if (fmvs.length==0) {
        					continue;
        				}
        				
        				tvTip_text = "正在合并第" + (i+1) + "段视频 ......";
        				Message msgt = new Message();
        				msgt.what = UPDATE_TIP;
        				mHandler.sendMessage(msgt);
        				
        				int fileLength = GetMVLength(fInputFiles[i]);
        				File mv = new File(tOutput.getText().toString() + GetMVName(fInputFiles[i]));
        				String sFileName = fInputFiles[i].listFiles()[0].toString();
        				sFileName = sFileName.substring(0, sFileName.lastIndexOf("_"));
        				FileOutputStream fout;
        				FileInputStream fin;
        				byte[] buf = new byte[ 1024 * 1024 * 10];
        				int iCount = 0;
        				int iTotal = 0;
        				try {
	        				if (!mv.exists()) {
	        					mv.createNewFile();
	        				}
            				fout = new FileOutputStream(mv.toString());
            				
            				for (int j=0; j<fmvs.length; j++) {
            					fin = new FileInputStream(sFileName + "_" + j + ".!mv");
            					while ((iCount=fin.read(buf))>0) {
            						Log.d("count", "iCount=" + iCount);
            						fout.write(buf);
            						iTotal = iTotal + iCount;
            						iProgress = iTotal / (fileLength/100);
                					Message msg = new Message();
                					msg.what = UPDATE_PROGRESS;
                					mHandler.sendMessage(msg);
            						
            					}
            					fin.close();
            				}
            				fout.close();
        				} catch (Exception e)
        				{
        					Log.e("ERROR", e.getMessage());
        					continue;
        				}
        				
        				
        				
//        				try {
//        					iProgress = i+1;
//        					Message msg = new Message();
//        					msg.what = UPDATE_PROGRESS;
//        					mHandler.sendMessage(msg);
//        					if (i==99) 
//        					{
//        						Message msgf = new Message();
//        						msgf.what = FINISHED;
//        						mHandler.sendMessage(msgf);
//        					}
//        					Thread.sleep(200);
//        				} catch (Exception e) {
//        					Log.e("thread", e.getMessage());
//        				}
        			}
        			
					Message msgf = new Message();
					msgf.what = FINISHED;
					mHandler.sendMessage(msgf);
        		}
        	});
        	
        	aThread.start();
    	}
    };
    
    private String GetMVName(File moviePath) {
    	String MovieName = "";
    	MovieName = moviePath.listFiles()[0].getName();
    	MovieName = MovieName.substring(0, MovieName.lastIndexOf("_"));
    	return MovieName;
    }
    
    private int GetMVLength(File moviePath) {
    	int fileLength = 0;
    	File[] files = moviePath.listFiles();
    	for (int i=0;i<files.length;i++) {
    		fileLength += files[i].length();
    	}
    	return fileLength;
    }

/*
    private Handler mHandler = new Handler() {
    	public void handleMessage(Message msg) {
    		switch (msg.what) {
    		case UPDATE_PROGRESS:
    			PB.setProgress(iProgress);
    			tvProgress.setText(iProgress + "%");
    			break;
    			
    		case FINISHED:
            	btMerge.setEnabled(true);
            	tInput.setEnabled(true);
            	tOutput.setEnabled(true);
    			break;
    			
    		case UPDATE_COUNT:
    			tvCount.setText(tvCount_text);
    			break;
    			
    		case UPDATE_TIP:
    			tvTip.setText(tvTip_text);
    			break;
    		}
    	}
    };
*/
    
    private static class MyHandler extends Handler {
        WeakReference<MargeMVActivity> mActivity;

        MyHandler(MargeMVActivity activity) {
                mActivity = new WeakReference<MargeMVActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
        	MargeMVActivity theActivity = mActivity.get();
                switch (msg.what) {
        		case UPDATE_PROGRESS:
        			theActivity.PB.setProgress(theActivity.iProgress);
        			theActivity.tvProgress.setText(theActivity.iProgress + "%");
        			break;
        			
        		case FINISHED:
        			theActivity.btMerge.setEnabled(true);
        			theActivity.tInput.setEnabled(true);
        			theActivity.tOutput.setEnabled(true);
        			break;
        			
        		case UPDATE_COUNT:
        			theActivity.tvCount.setText(theActivity.tvCount_text);
        			break;
        			
        		case UPDATE_TIP:
        			theActivity.tvTip.setText(theActivity.tvTip_text);
        			break;
                }
        }
    };

    private MyHandler mHandler = new MyHandler(this);
}